package com.daybreak.component_security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

/**
 * 自定义的鉴权服务，通过鉴权的才能继续访问某个请求
 */
@Component("rbacService")
public class MyRBACService {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;
        if (principal instanceof UserDetails) { //首先判断先当前用户是否是我们UserDetails对象。
            UserDetails userDetails = (UserDetails) principal;

            Set<String> urls = new HashSet<>(); // 数据库读取 //读取用户所拥有权限的所有URL

            for(GrantedAuthority ga : userDetails.getAuthorities()){
                urls.add(ga.getAuthority());
            }


            // 注意这里不能用equal来判断，因为有些URL是有参数的，所以要用AntPathMatcher来比较
            for (String url : urls) {
                String requestUrl = request.getRequestURI();
                System.out.println("访问路径：" + requestUrl);
                System.out.println("当前拥有的权限url：" + url);
                if (antPathMatcher.match("/" + url, requestUrl)) {
                    hasPermission = true;
                    break;
                }
            }
        }
        return hasPermission;
    }
}
